#!/bin/sh
# thanks to http://1000umbrellas.com/2010/10/05/updated-how-to-automatically-move-and-remove-transmission-daemon-downloads
# script to check for complete torrents in transmission folder, then stop and move them

# this script use transmission-remote, from transmission-cli
# sudo apt-get install transmission-cli

if [ "$#" -eq 1 ] && [ -d "$1" ]; then
	# set MOVEDIR using the first command-line argument
	MOVEDIR=$1 # the folder to move completed downloads to	
else
	# explain why...
	echo "you must provide a valid folder path"
	exit 1 # and exit
fi

# use transmission-remote to get torrent list from transmission-remote list
# use sed to delete first / last line of output, and remove leading spaces
# use cut to get first field from each line
TORRENTLIST=`transmission-remote --list | sed -e '1d;$d;s/^ *//' | cut --only-delimited --delimiter=" " --fields=1`

# for each torrent in the list
for TORRENTID in $TORRENTLIST
do
        NAME=`transmission-remote --torrent $TORRENTID --info | grep "Name: " | sed 's/^ *//g'`
        echo "** $TORRENTID) $NAME"

        # check if torrent download is completed
        DL_COMPLETED=`transmission-remote --torrent $TORRENTID --info | grep "Percent Done: 100%"`

        # check torrent’s current state is “Stopped”, “Finished”, or “Idle”
        STATE_STOPPED=`transmission-remote --torrent $TORRENTID --info | grep "State: Stopped\|Finished\|Idle"`

        # if the torrent is “Stopped”, “Finished”, or “Idle” after downloading 100%…
        if [ "$DL_COMPLETED" != "" ] && [ "$STATE_STOPPED" != "" ]; then
                # move the files and remove the torrent from Transmission
                echo " Torrent #$TORRENTID is completed."
                echo "  Moving downloaded file(s) to $MOVEDIR."
                transmission-remote --torrent $TORRENTID --move $MOVEDIR
                echo "   Removing torrent from list."
                transmission-remote --torrent $TORRENTID --remove
        else
                echo " Torrent #$TORRENTID is not completed. Ignoring."
        fi

done 


